package com.company.gameserver;

import com.company.Card;
import com.google.gson.Gson;

import java.util.*;
import java.util.stream.Collectors;

class GameState {
    private List<Card> deck;
    private Map<String, List<Card>> playerHands = new HashMap<>();
    private List<Card> lastPlayedCards = new ArrayList<>();
    private String currentPlayer;
   //FIXME private String lastPlayer=""; // 上一次完成出牌者
    private List<String> players = new ArrayList<>();
    private String gameStatus = "WAITING"; // WAITING, PLAYING, FINISHED

    @Override
    public String toString() {
        return "GameState{" +
                "players=" + players +
                ", gameStatus='" + gameStatus + '\'' +
                '}';
    }

//FIXME    public String getLastPlayer() {
//        return lastPlayer;
//    }
//
//FIXME     public void setLastPlayer(String lastPlayer) {
//        this.lastPlayer = lastPlayer;
//    }

    public synchronized void addPlayer(String playerName) {
        if (!players.contains(playerName)) {
            players.add(playerName);
            playerHands.put(playerName, new ArrayList<>());
        }
    }

    public synchronized void removePlayer(String playerName) {
        players.remove(playerName);
        playerHands.remove(playerName);
    }

    public synchronized void initializeGame() {
        if (players.size() < 2) return;
        System.out.println("创建并洗牌");
        // 创建并洗牌
        deck = Card.createDeck();
        Collections.shuffle(deck);

        // 发牌
        int playerCount = players.size();
        for (int i = 0; i < deck.size(); i++) {
            String player = players.get(i % playerCount);
            playerHands.get(player).add(deck.get(i));
        }

        // 排序手牌
        for (List<Card> hand : playerHands.values()) {
            Collections.sort(hand);
        }

        // 确定先出牌的玩家(持有黑桃3的玩家)
        for (String player : players) {
            if (hasCard(player, "♠", "3")) {
                currentPlayer = player;
                break;
            }
        }
        if (currentPlayer == null) {
            currentPlayer = players.get(0);
        }

        System.out.println("currentPlayer:"+currentPlayer);
        System.out.println(playerHands.toString());
        gameStatus = "PLAYING";
        lastPlayedCards.clear();
    }

    public synchronized boolean playCards(String player, List<Card> cards) {

        if (!player.equals(currentPlayer)) return false;
        if (!playerHands.get(player).containsAll(cards)) return false;

//FIXME        if (this.lastPlayer.equals(currentPlayer)){
//            //如果上一轮出牌的是自己，则可以出任一牌类型
//            this.lastPlayedCards.clear();
//        }

        // 验证牌型
        int cardType = Card.getCardType(cards);
        if (cardType == -1) return false;

        // 验证是否符合出牌规则
        if (!lastPlayedCards.isEmpty()) {
            int lastType = Card.getCardType(lastPlayedCards);
            if (cardType != lastType && cardType != Card.BOMB && cardType != Card.KING_BOMB) {
                return false;
            }
            if (Card.getCardsWeight(cards) <= Card.getCardsWeight(lastPlayedCards)) {
                return false;
            }
        }

        // 出牌
        playerHands.get(player).removeAll(cards);
        lastPlayedCards = cards;
//FIXME        this.lastPlayer = player;

        // 轮到下一个玩家
        int currentIndex = players.indexOf(currentPlayer);
        currentPlayer = players.get((currentIndex + 1) % players.size());

        return true;
    }

    public synchronized void pass(String player) {
        if (!player.equals(currentPlayer)) return;


        // 只有不是首轮才能跳过
        if (!lastPlayedCards.isEmpty()) {
            int currentIndex = players.indexOf(currentPlayer);
            currentPlayer = players.get((currentIndex + 1) % players.size());
        }
    }

    public synchronized boolean isGameOver() {
        for (String player : players) {
            if (playerHands.get(player).isEmpty()) {
                return true;
            }
        }
        return false;
    }

    public synchronized String getWinner() {
        for (String player : players) {
            if (playerHands.get(player).isEmpty()) {
                return player;
            }
        }
        return null;
    }

    private boolean hasCard(String player, String suit, String rank) {
        return playerHands.get(player).contains(new Card(suit, rank));
    }
    private static final Gson gson = new Gson();

    public String toJson() {
        // 准备要序列化的数据
        Map<String, Object> stateData = new HashMap<>();
        stateData.put("currentPlayer", currentPlayer);
        stateData.put("lastPlayedCards", lastPlayedCards.stream()
                .map(Card::toString).collect(Collectors.toList()));
        stateData.put("gameStatus", gameStatus);
        stateData.put("players", players);

        // 转换玩家手牌
        Map<String, List<String>> handsData = new HashMap<>();
        for (Map.Entry<String, List<Card>> entry : playerHands.entrySet()) {
            handsData.put(entry.getKey(),
                    entry.getValue().stream()
                            .map(Card::toString)
                            .collect(Collectors.toList()));
        }
        stateData.put("playerHands", handsData);

        return gson.toJson(stateData);
    }

    // Getter methods
    public String getCurrentPlayer() { return currentPlayer; }
    public String getGameStatus() { return gameStatus; }
}